import { asyncRoutes, constantRoutes } from '@/router'
// import { formatTreeRole } from '@/utils/index'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route, level) {
  if (route.path === '*') {
    return true
  }
  const filterMenu = roles.find((item) => String(item.level_num) === String(level) && route.meta.title === item.name)
  return Boolean(filterMenu)
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles, level = 1) {
  const res = []
  for (let index = 0; index < routes.length; index++) {
    const route = routes[index]

    const tmp = { ...route }
    if (hasPermission(roles, tmp, level)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles, level + 1)
      }
      res.push(tmp)
    }
  }
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve) => {
      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //  accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      commit('SET_ROUTES', accessedRoutes)

      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
